//
//  YFRacquetController.m
//  SquashSpark
//
//  Created by Coollang on 2017/11/15.
//  Copyright © 2017年 Coollang-YF. All rights reserved.
//

#import "YFRacquetController.h"
#import "UserSaveItem.h"
#import "UserGroup.h"
#import "UserCenterCell.h"
#import "UIView+Frame.h"
#import "YFLoginApi.h"
#import <YYKit/YYKit.h>
#import "YFLoginHelper.h"
#import "YFEquipmentCalibrationVC.h"

NSString * const kUpdateRacquetTypeNoti = @"kUpdateRacquetTypeNoti";

@interface YFRacquetController ()
@property (strong, nonatomic) UITableView *tableView;
/** 当前选中的类型 */
@property (nonatomic, strong) UserSaveItem *selectSaveItem;

@property (nonatomic, strong) YYLabel *bottomTipLabel;


/** 原选择的类型 */
@property (nonatomic, assign)RacquetType originalRacquetType;

@end

@implementation YFRacquetController

- (void)loadView {
    self.tableView = [[UITableView alloc] initWithFrame:[UIScreen mainScreen].bounds style:UITableViewStylePlain];
    self.view = self.tableView;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.backgroundColor = kSeparationLineColor;
    self.tableView.separatorStyle = UITableViewCellSelectionStyleNone;
    if (self.isWecomeRacquetVc) {
        self.tableView.tableFooterView = [self creatTableViewButtonFooterView];
    }else {
        if (self.cacheUserInfoItem == nil) {
            self.cacheUserInfoItem = [User getUseInfo];
        }
        self.tableView.tableFooterView = [self creatTableViewYYLabelFooter];
    }
    self.originalRacquetType = self.cacheUserInfoItem.racquetType;
    self.title = @"My Racquet Profile";
    [self loadItemDatasource];
}
- (void)customBaseBackNavBarItemAction:(UIBarButtonItem *)backItem {
    if (self.isWecomeRacquetVc == NO) {
        [YFLoginHelper uploadUserInfoWithInfoItem:_cacheUserInfoItem completed:^(NSError *error) {
            
        }];
    }
    if (self.presentingViewController) {
        [self dismissViewControllerAnimated:YES completion:nil];
    } else {
        [self.navigationController popViewControllerAnimated:YES];
    }
}
- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    if (self.isWecomeRacquetVc == NO) {
        __weak typeof(self) weakSelf = self;
        [YFLoginHelper uploadUserInfoWithInfoItem:_cacheUserInfoItem completed:^(NSError *error) {
            if (weakSelf.originalRacquetType != _cacheUserInfoItem.racquetType) {
                [[RLMRealm defaultRealm] beginWriteTransaction];
                [User getUseInfo].equipmentCalibration = NO;
                [[RLMRealm defaultRealm] commitWriteTransaction];
                // 发送需要校验的通知
                [[NSNotificationCenter defaultCenter] postNotificationName:kUpdateRacquetTypeNoti object:@(error == nil)];
            }
        }];
    }
}

- (void)loadItemDatasource {
    UserGroup *group0 = [[UserGroup alloc] init];
    
    RacquetType racquetType = RacquetLight;
    if (_cacheUserInfoItem != nil) {
        racquetType = _cacheUserInfoItem.racquetType;
    }
    UserSaveItem *item0_0 = [UserSaveItem itemWithTitle:[SquashEnum stringWithRacquet:RacquetVeryLight] andSubTitle:nil withSelect:racquetType == RacquetVeryLight];
    item0_0.argument = @(RacquetVeryLight);
    UserSaveItem *item0_1 = [UserSaveItem itemWithTitle:[SquashEnum stringWithRacquet:RacquetLight] andSubTitle:nil withSelect:racquetType == RacquetLight];
    item0_1.argument = @(RacquetLight);
    
    UserSaveItem *item0_2 = [UserSaveItem itemWithTitle:[SquashEnum stringWithRacquet:RacquetOrdinary] andSubTitle:nil withSelect:racquetType == RacquetOrdinary];
    item0_2.argument = @(RacquetOrdinary);
    UserSaveItem *item0_3 = [UserSaveItem itemWithTitle:[SquashEnum stringWithRacquet:RacquetHeavy] andSubTitle:nil withSelect:racquetType == RacquetHeavy];
    item0_3.argument = @(RacquetHeavy);
    [group0.items addObjectsFromArray:@[item0_0,item0_1,item0_2,item0_3]];
    
    __weak typeof(self) weakSelf = self;
    for (UserSaveItem *saveItem in group0.items) {
        if(saveItem.isSelected == YES){
            weakSelf.selectSaveItem = saveItem;
        }
        [saveItem setBlock:^(UserItem *itemT,NSIndexPath *indexPath) {
            UserSaveItem *saveItem = (UserSaveItem *)itemT;
            if (![weakSelf.selectSaveItem isEqual:saveItem]) {
                saveItem.isSelected = !saveItem.isSelected;
                weakSelf.selectSaveItem.isSelected = NO;
                weakSelf.selectSaveItem = saveItem;
            }
        }];
    }
    [self.groups addObject:group0];
}

- (void)setSelectSaveItem:(UserSaveItem *)selectSaveItem {
    _selectSaveItem = selectSaveItem;
    if (self.isWecomeRacquetVc) {
        _cacheUserInfoItem.racquetType = [selectSaveItem.argument integerValue];
    }else {
        [[RLMRealm defaultRealm] beginWriteTransaction];
        _cacheUserInfoItem.racquetType = [selectSaveItem.argument integerValue];
        [[RLMRealm defaultRealm] commitWriteTransaction];
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UserCenterCell *cell = [UserCenterCell settingViewCellTableView:tableView withStyle:UITableViewCellStyleSubtitle];
    UserGroup *group = self.groups[indexPath.section];
    UserItem *item = group.items[indexPath.row];
    cell.item = item;
    if (indexPath.row ==  group.items.count - 1) {
        [cell showSeparationBottomLine:NO];
    }else {
        [cell showSeparationBottomLine:YES];
    }
    cell.separationBottomLineHeight = 7;
    cell.bottomLineView.backgroundColor = kSeparationLineColor;

    cell.textLabel.textColor = kTWhiteText;
    cell.textLabel.font = kOpenSansFont(OpenSansBold, 16);
    cell.detailTextLabel.textColor = kTWhiteText;
    cell.detailTextLabel.font = kOpenSansFont(OpenSansRegular, 12);

//    cell.textLabelVOffset = 6;
//    cell.detailLabelVOffset = -6;

    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    UserGroup *group = self.groups[indexPath.section];
    if (indexPath.row == group.items.count - 1) {
        return kAutoHei(67);
    }else {
        return kAutoHei(67) + 7;
    }
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 0;
}

- (UIView *)creatTableViewButtonFooterView {
    UIView *footerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kYFScreenWidth, kAutoHei(140))];
    footerView.backgroundColor = kSeparationLineColor;
    UIButton *nextButton = [UIButton buttonWithType:UIButtonTypeSystem];
    [nextButton setTitle:@"NEXT" forState:UIControlStateNormal];
    [nextButton addTarget:self action:@selector(nextbuttonClick:) forControlEvents:UIControlEventTouchUpInside];
    nextButton.backgroundColor = kYellowGreenColor;
    nextButton.titleLabel.font = kOpenSansFont(OpenSansExtraBold, 16);
    [nextButton setTitleColor:kTBlackText forState:UIControlStateNormal];
    [nextButton clipsCornerRadius:3 borderWidth:0 borderColor:nil];
    [footerView addSubview:nextButton];
    [nextButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(footerView);
        make.height.mas_equalTo(kAutoHei(50));
        make.width.mas_equalTo(kAutoWid(267));
        make.centerX.equalTo(footerView.mas_centerX).offset(10);
    }];
    return footerView;
}

- (UIView *)creatTableViewYYLabelFooter {
    YYLabel *label = [[YYLabel alloc] init];
    label.numberOfLines = 0;
    self.bottomTipLabel = label;
    NSString *labelText = @"After setting up the racket parameters,please re calibrate the equipment";
    label.text = labelText;
    [self configueryy_Label:label string:labelText hightlightStr:@"please re calibrate the equipment"];
    CGSize labelSzie = [label sizeThatFits:CGSizeMake(kYFScreenWidth, MAXFLOAT)];
    label.frame = CGRectMake(16, 26, labelSzie.width, labelSzie.height + 4);
    UIView *footerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kYFScreenWidth, CGRectGetMaxY(label.frame))];
    
    [footerView addSubview:label];
    return footerView;
}

- (void)configueryy_Label:(YYLabel *)yy_label string:(NSString *)joinString hightlightStr:(NSString *)highlightStr {
    
    yy_label.displaysAsynchronously = YES;
    
    // 计算文本内容的大小
    NSRange joinrange = [joinString rangeOfString:highlightStr];
    NSMutableAttributedString *joinText = [[NSMutableAttributedString alloc] initWithString:joinString];
    joinText.font = kOpenSansFont(OpenSansRegular, 13);
    joinText.color = kTLightGray999;
    
    joinText.lineSpacing = 8;
    [joinText setUnderlineStyle:NSUnderlineStyleSingle];
    [joinText setUnderlineColor:[UIColor clearColor]];
    joinText.baselineOffset = @2;
    joinText.alignment = NSTextAlignmentLeft;
    
    [joinText setUnderlineColor:kTWhiteText range:joinrange];
    [yy_label sizeToFit];
    
    [joinText setTextHighlightRange:joinrange color:kTWhiteText backgroundColor:[UIColor clearColor] tapAction:^(UIView * _Nonnull containerView, NSAttributedString * _Nonnull text, NSRange range, CGRect rect) {
        // 跳转到设备校验页面
        YFEquipmentCalibrationVC *equipmentVc = [[YFEquipmentCalibrationVC alloc] initWithNibName:@"YFEquipmentCalibrationVC" bundle:nil];
        equipmentVc.isWecomeEquipmentVc = self.isWecomeRacquetVc;
        [self.navigationController pushViewController:equipmentVc animated:YES];
    }];
    yy_label.attributedText = joinText;
}

- (void)nextbuttonClick:(UIButton *)sender {
    // 将数据上传到网络
    [self.hud show];
    [YFLoginHelper uploadUserInfoWithInfoItem:_cacheUserInfoItem completed:^(NSError *error) {
        [self.hud dismiss];
        if (error == nil) {
            if (self.nextButtonClick) {
                self.nextButtonClick();
            }
        }else {
            [self.hud showErrorWithString:@"Upload fail" dimissAfterSecond:1.5];
            NSLog(@"%@",error.domain);
        }
    }];
}

@end
